<template>
  <div
    :style="{ paddingTop: `${searchBarTop}px` }"
    class="healthDetail relative px-34rpx pt-50rpx">
    <image
      :src="`${cdnUrl}/imgs/noOpen/bg.png${imgVersion}`"
      mode="scaleToFill"
      class="pointer-events-none fixed bottom-0 left-0 right-0 top-0 z--9 h-100% w-100%"
    />
    <div @click="goHealthBack">
      <div class="z-999 mb-16rpx flex items-center">
        <uni-icons type="back" size="28" />
      </div>
    </div>
    <div class="mb-62rpx mt-46rpx w-100% flex items-center">
      <div class="mr-16rpx w-100rpx text-24rpx text-hex-7C8699">测评进度</div>
      <div class="mr-16rpx h-32rpx w-70% rounded-46rpx bg-[rgb(232,242,199)]">
        <div class="progress relative h-32rpx rounded-46rpx"
             :style="{ width: `${questionPercent}%`, transition: 'width 1s ease' }">
          <div class="masker absolute rounded-46rpx" />
          <image
            :src="`${cdnUrl}/imgs/healthDetail/progress.png${imgVersion}`"
            mode="scaleToFill"
            class="absolute bottom-32rpx h-50rpx w-56rpx -right-15rpx"
          />
        </div>
      </div>
      <div class="w-80rpx">
        <text class="text-hex-abcd03">{{ questionsNum }}</text>
        <text class="text-hex-999">/{{ questionList.length }}</text>
      </div>
    </div>
    <div
      v-if="upQuestionShow || downQuestionShow"
      class="fixed bottom-0 left-0 right-0 rounded-t-36rpx bg-hex-ffffff py-32rpx">
      <div class="flex items-center justify-around text-28rpx font-bold text-hex-abcd04">
        <div
          v-if="upQuestionShow"
          class="btn-normal-bg h-76rpx w-230rpx flex items-center justify-center rounded-56rpx"
          :class="{ activeWidth: !downQuestionShow }"
          @click="getUpQuestion"
        >上一题</div>
        <div
          v-if="downQuestionShow"
          class="btn-normal-bg h-76rpx w-230rpx flex items-center justify-center rounded-56rpx"
          :class="{ activeWidth: !upQuestionShow }"
          @click="getDownQuestion"
        >下一题</div>
      </div>
    </div>
    <!-- <div class="mt-32rpx text-center" />
    <div class="mb-56rpx mt-32rpx box-border flex justify-between">
      <div>
        <div v-if="questionText"
             class="font-alimamaShuHeiTi mb-16rpx w-234rpx text-38rpx font-600" :class="{ 'w-260rpx': questionType==='1' || questionType==='2' }">
          {{ questionText }}
        </div>
        <div class="text-24rpx text-hex-7C8699">✍🏻认真填写测评更精准~</div>
      </div>
      <div>
        <image
          :src="`${cdnUrl}/imgs/healthDetail/icon.png${imgVersion}`"
          mode="scaleToFill"
          class="h-146rpx w-146rpx"
        />
      </div>
    </div> -->
    <div
      v-if="questionitem"
    >
      <div
        v-if="questionitem.content"
        class="activeclass mb-48rpx min-h-50rpx w-100% text-36rpx font-600">{{ questionitem.content }}</div>
      <div
        v-for="item in questionitem.options"
        class="activeclass mb-32rpx box-border h-120rpx w-100% flex items-center justify-between rounded-32rpx bg-hex-ffffff px-32rpx text-28rpx text-hex-7C8699"
        :class="{ 'btn-theme-bg': item.isSelected } "
        @click="answerItem(item)"
      >
        <div>{{ item.name }}.  {{ item.content }}</div>
        <div>
          <image
            :src="`${cdnUrl}/imgs/healthDetail/select.png${imgVersion}`"
            mode="scaleToFill"
            class="h-32rpx w-32rpx"
          />
        </div>
      </div>
    </div>
    <confirm ref="confrimPop" />
  </div>
</template>

<script lang="ts" setup>


let questionType: any = $ref('')
let recordId: any = $ref('')
// let questionText: any = $ref('')
// let questionTypeName: any = $ref('')
let questionList: any = $ref([])
let searchBarTop: any = $ref('24')
let currentIndex: any = $ref('')

onLoad((options) => {
  if (options) {
    questionType = options.questionType
    recordId = options.evaluationId
    currentIndex = options?.spliceIndex
    // switch (questionType) {
    //   case '1':
    //     questionText = '测试一下你的生理期问题吧~'
    //     questionTypeName = '生理期问题'
    //     break
    //   case '2':
    //     questionText = '免疫力要提高才能减少疾病~'
    //     questionTypeName = '提高免疫力'
    //     break
    //   case '3':
    //     questionText = '测试一下你的脾胃问题吧~'
    //     questionTypeName = '脾胃问题'
    //     break
    //   case '4':
    //     questionText = '测试一下你的超重问题吧~'
    //     questionTypeName = '超重问题'
    //     break
    //   case '5':
    //     questionText = '测试一下你的头发问题吧~'
    //     questionTypeName = '头发问题'
    //     break
    //   case '6':
    //     questionText = '测试一下你的皮肤问题吧~'
    //     questionTypeName = '头发问题'
    //     break
    //   case '7':
    //     questionText = '测试一下你的睡眠问题吧~'
    //     questionTypeName = '睡眠问题'
    //     break
    //   case '8':
    //     questionText = '测试你是属于什么体质~'
    //     questionTypeName = '体质问题'
    //     break
    //   case '9':
    //     // questionText = '测试一下你的综合问题吧~'
    //     questionTypeName = '综合测评'
    //     break
    //   default:
    //     break
    // }
  }
  // #ifndef H5
  let menuButtonInfo = uni.getMenuButtonBoundingClientRect()
  searchBarTop = menuButtonInfo.top
  // #endif
  // getQuestionList()
})
const goback = () => {
  uni.navigateBack({
    delta: 1,
  })
}
let confrimPop: any = $ref()

const getQuestionList = async () => {
  const reqData = {
    method: 'get',
    data: {
      questionCategoryId: questionType,
      evaluationId: recordId,
    },
  }
  const { data, status, error } = await Fetch('/qqyapi/health/questions/wholeQuestionnaire', reqData)
  if (status === 200) {

    questionList = data.result.questions
    questionList.forEach((item) => {
      item.options.forEach(option => {
        if (option.selected === true) {
          option.isSelected = 1
        } else {
          option.isSelected = 0
        }
      })
    })

    let tempIndex = 0
    if (currentIndex !== '0') {
      tempIndex = questionList.findIndex((item) => item.id === currentIndex)
      tempIndex = tempIndex + 1
    }
    spliceIndex = tempIndex
    currentQuestion = tempIndex
    questionsNum = spliceIndex + 1

    if (spliceIndex >= 1) {
      upQuestionShow = true
    }
    if (spliceIndex >= questionList.length - 1) {
      spliceIndex = questionList.length - 1
      questionsNum = spliceIndex + 1
    }
    questionitem = questionList[spliceIndex]
  }
}

// 更新测评记录
const upDateEvaluation = async (questionId, optionId) => {
  // console.log(questionId, optionId, 'id')

  const reqData = {
    method: 'put',
    data: {
      id: Number(recordId),
      question_id: Number(questionId), //问题编码
      question_option_id: Number(optionId), //问题选项编码
    },
  }
  const { data, status, error } = await Fetch('/api/s/health/evaluations', reqData)
}

//问题：七大答题回调
const addWaterList = useThrottleFn(async (item) => {

  const reqData = {
    method: 'post',
    data: {
      question_category_id: questionType, //问题类型编码
      evaluation_id: recordId, //测评记录编码
      question_id: item.questionId, //问题编码
      questionnaire_id: null, //问卷编码
      question_option_id: item.id, //问题选项编码
    },
  }
  const { data, status, error } = await Fetch('/api/s/health/evaluationFlows', reqData)
  if (status !== 200 || data.code !== 0) {
    return
  }
  questionList.forEach((nowItem) => {
    if (nowItem.id === item.questionId) {
      nowItem.options.forEach((optionItem) => {
        if (optionItem.id === item.id) {
          optionItem.isSelected = 1
        } else {
          optionItem.isSelected = 0
        }
      })
    }
  })
  upDateEvaluation(item.questionId, item.id)
  changeQuestionOption(item.id)
}, 500)

const comprehensiveData = useThrottleFn((item) => {
  questionList.forEach((nowItem) => {
    if (nowItem.id === item.questionId) {
      nowItem.options.forEach((optionItem) => {
        if (optionItem.id === item.id) {
          optionItem.isSelected = 1
        } else {
          optionItem.isSelected = 0
        }
      })
    }
  })
  if (questionitem && questionitem.options.some(obj => obj.isSelected === 1)) {
    changeQuestionOption(item.id)
  }
  
}, 500)

let stats = $ref([
  { group_tag: '起居', score: 0 },
  { group_tag: '饮食', score: 0 },
  { group_tag: '运动', score: 0 },
  { group_tag: '心理', score: 0 },
  { group_tag: '营养', score: 0 },
])
const statsData = () => {
  //提取用户答题答案分值
  questionList.forEach(item => {
    item.options.forEach(curItem => {
      if (curItem.isSelected) {
        item.score = Number(curItem.score)
      }
    })
  })
  //将题目类型分组，并计算总值
  stats.forEach(sItem => {
    questionList.forEach(qItem => {
      if (sItem.group_tag === qItem.groupTag) {
        sItem.score += qItem.score
      }
    })
  })
  //将每组数据传给后端
  comprehensiveQuestion(stats)

}
//综合测评：答题回调
const comprehensiveQuestion = async (list) => {
  const params = list.map((item) => {
    item.evaluation_id = recordId
    return item
  })
  const reqData = {
    method: 'post',
    data: params,
  }
  const { data, status, error } = await Fetch('/api/s/health/generalScores', reqData)
}

//答题
const answerItem = async (item) => {
  switch (questionType) {
    case '1':
    case '2':
    case '3':
    case '4':
    case '5':
    case '6':
    case '7':
      addWaterList(item)
      break
    case '9':
      comprehensiveData(item)
      break
    default:
      break
  }
}
let questionitem: any = $ref()//当前页面展示的题目
let spliceIndex: any = $ref(0)//展示数组第几个
let upQuestionShow: any = $ref(false)//是否展示上一题按钮
let downQuestionShow = $ref(false)//是否展示展示下一题按钮
let currentQuestion: any = $ref('0')//当前的题目
let questionsNum = $ref(1)

const getQuestionItem = () => {
  if (spliceIndex >= 1) {
    upQuestionShow = true
  }
  if (spliceIndex <= 0) {
    upQuestionShow = false
    spliceIndex = 0
  }
  // console.log(Number(spliceIndex), Number(currentQuestion), '大小')

  if (Number(spliceIndex) < Number(currentQuestion)) {
    downQuestionShow = true
  } else {
    downQuestionShow = false
  }
  // 如果相等点击的选项等于长度就跳转到报告页面
  if (spliceIndex === questionList.length) {
    if (questionType === '9') {
      statsData()
    }
    setTimeout(() => {
      uni.navigateTo({
        url: `/pages-health/healthReport?evaluationId=${recordId}&type=${questionType}`,
      })
    }, 600)
    return
  }
  questionitem = questionList[spliceIndex]
  if (spliceIndex + 1 <= questionList.length) {
    questionsNum = spliceIndex + 1
  } else {
    questionsNum = questionList.length
  }
}
const questionPercent = $computed(() => {
  return questionsNum * 100 / questionList.length
})
const changeQuestionOption = (index) => {
  spliceIndex++
  if (Number(spliceIndex) > Number(currentQuestion)) {
    currentQuestion = spliceIndex
  }
  questionitem = []
  getQuestionItem()
}
// 上一题
const getUpQuestion = useThrottleFn(() => {
  spliceIndex--
  getQuestionItem()
}, 500)
const getDownQuestion = useThrottleFn(() => {
  if (spliceIndex === Number(currentQuestion)) {
    downQuestionShow = false
    return
  }
  spliceIndex++
  getQuestionItem()
}, 500)

// //监听题目变化，改变题目文案
// watch(() => questionitem, () => {
//   nextTick(() => {
//     changeText()
//   })
// }, { immediate: true, deep: true })

// const changeText = () => {
//   if (questionType === '9' && questionitem) {
//     if (questionitem.groupTag === '心理') {
//       questionText = '心理健康需重视~'
//     } else if (questionitem.groupTag === '营养') {
//       questionText = '营养到位健康生活~'
//     } else {
//       questionText = '养成好的习惯才能更好享受生活~'
//     }
//   }
// }

onMounted(() => {
  getQuestionList()
})

</script>

<style lang="scss" scoped>

.healthDetail{
  .active{
    background: #29B897 ;
    color: #fff;
  }

  .font-alimamaShuHeiTi{
    font-family:alimamaShuHeiTi;
  }

  @keyframes wrapper-gradient {
    // 0% {
    //   transform: translateY(100%);
    // }

    // 100% {
    //   transform: translateY(0);
    // }
    0% {
      transform:translate(-100px);
      opacity:0;
    }

    50% {
      transform:translate(-20px);
      opacity:.5;
    }

    100% {
      transform:translate(0);
      opacity:1;
    }
  }

  .activeclass {
    overflow: hidden;
    animation: wrapper-gradient .1s linear;
    transform:translate(0);
    transition-delay: .1s;
  }

  .progress {
    background: linear-gradient(-45deg, #45E9C3 36%, #ABCD03 28%, #ABCD03 67%, #45E9C3 25%);
    background-size: 18px 16px;
    animation: load 1s;

    .masker {
      inset: 0;
      opacity: .8;

      // background: linear-gradient(90deg, #1c7bda 20%, #fff 100%)
      background: #ABCD03;
    }

  }

  @keyframes load {
    0% {
      width: 0;
    }
  }

  .activeWidth{
    width: 492rpx;
  }
}
</style>
